using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.ObjectModel;
using LispInterpretor.HelperClasses;

namespace LispInterpretor.InBuiltProcedures
{
    internal class UserDefinedProcedure : Procedure
    {
        private Environment capturedEnvironment;
        private IList<string> parameters;
        private string procedureBody;

        public UserDefinedProcedure(string argumentList, string expressionBody, Environment env)
        {
            capturedEnvironment = env;
            procedureBody = expressionBody;
            parameters = ParserHelper.ParseArguments(argumentList);

        }

        public override object Apply(params object[] args)
        {
            Check.IsTrue(args.Length == parameters.Count, "Incorrect number of arguments.");

            Environment newEnvironment = new Environment(capturedEnvironment);

            for (int i = 0; i < args.Length; i++)
            {
                newEnvironment.Add(parameters[i], args[i]);
            }

            return Evaluator.Eval(procedureBody, newEnvironment);
        }
    }
}
